package com.scalar.chiptrack.operations.dataentry.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.forms.DieBankTransitForm;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.release.dao.RelaseDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: ChandraSekhar
 * Date: Feb 08, 2008
 * Time: 3:16:35 PM
 */

public class DieBankTransitAction extends ChipTrackAction implements SessionKeys, Constants
{
    private static final String ACTION_NAME = "/dieBankTransit.do";

    public ActionForward execute(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        HashMap errors          = new HashMap();
		HashMap info            = new HashMap();
        String actionForword    = "success";
        String action           = request.getParameter ("action");
        DieBankTransitForm dieBankTransitForm = (DieBankTransitForm)form;
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        ArrayList diebankWipLotList     = new ArrayList();
        ArrayList dbReceiveLotList      = new ArrayList();
        ArrayList waferInfoList      = new ArrayList();
        HttpSession session = request.getSession ();
        DBTransaction dbTranasaction    = null;

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME  );
            return ( mapping.findForward ( "login" ) );
        }

        if ( action == null )
        {
            action = "";
        }

        LotDetails  lotProcessDetails = new LotDetails();
        ArrayList vendorList = new ArrayList();

        if ( action.equals("") )
		{
            try
            {
                dieBankTransitForm.setProcessStepId(0);
                dieBankTransitForm.setLocationId(0);
                dieBankTransitForm.setLotId(0);
                dieBankTransitForm.setWipLotsList( null );
                dieBankTransitForm.setAssyRelease( true );

                if ( user.getVendorId() > 0 ) // for VENDOR INTERFACE
                {
                    if (dieBankTransitForm.getLocationId() == 0 )
                    {
                        vendorList = VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_DIE_BANK, user.getVendorId() );
                        if ( vendorList != null && vendorList.size() > 0 )
                        {
                            dieBankTransitForm.setLocationId( Integer.parseInt ( ( (LabelValueBean)vendorList.get(0) ).getValue() ) );
                        }
                        else
                        {
                            dieBankTransitForm.setLocationId( -1 );
                        }
                    }
                }

                diebankWipLotList = DataEntryDAO.loadAllDieBankWipLots(dieBankTransitForm.getProcessStepId(), dieBankTransitForm.getLocationId(), dieBankTransitForm.getLotId(), dieBankTransitForm.isAssyRelease()  );

                if ( diebankWipLotList == null || diebankWipLotList.size() == 0 )
                {
                    info.put("No WIP lots available" , null );
                }

                dieBankTransitForm.setWipLotsList( diebankWipLotList );

                request.setAttribute("lotsList", diebankWipLotList );
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_DIE_BANK, user.getVendorId() ) );
                request.setAttribute("nextLocations",  RelaseDAO.loadProcessVendors( LOCATION_TYPE_ASSEMBLY ) );
                request.setAttribute("reciveProcessList", lotProcessDetails.getReceiveProcessList() );
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
		else if ( action.equalsIgnoreCase ( "search" ) )
		{
            actionForword = "search";
            try
            {
                diebankWipLotList = DataEntryDAO.loadAllDieBankWipLots(dieBankTransitForm.getProcessStepId(), dieBankTransitForm.getLocationId(), dieBankTransitForm.getLotId(), dieBankTransitForm.isAssyRelease()  );

                if ( diebankWipLotList == null || diebankWipLotList.size() == 0 )
                {
                    info.put("No WIP lots available" , null );
                }

                dieBankTransitForm.setWipLotsList( diebankWipLotList );

                request.setAttribute("nextLocations",  RelaseDAO.loadProcessVendors( LOCATION_TYPE_ASSEMBLY ) );
                request.setAttribute("reciveProcessList", lotProcessDetails.getReceiveProcessList() );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_DIE_BANK, user.getVendorId() ) );
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("lotsList", DataEntryDAO.loadAllDieBankWipLots( 0, dieBankTransitForm.getLocationId(), 0, dieBankTransitForm.isAssyRelease()  ) );
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        else if ( action.equalsIgnoreCase("save") )
        {
        	actionForword = "save";
            LotDetails lotDetails = null;
            LotDetails newlotDetails = null;
            LotDetails sortBinlotDetails = null;

            try
            {
                if ( dieBankTransitForm.getWipLotsList() != null && dieBankTransitForm.getWipLotsList().size() > 0 )
                {
                   for( int i=0; i < dieBankTransitForm.getWipLotsList().size(); i++)
                    {
                        lotDetails = (LotDetails)dieBankTransitForm.getWipLotsList().get(i);

                        if ( lotDetails.isChecked() )
                        {
                            if ( lotDetails.getCheckedWaferIdsAsString() == null || lotDetails.getCheckedWaferIdsAsString().equals("") )
                            {
                                lotDetails.setCheckedWaferIdsAsString( lotDetails.getWaferIds() );
                                lotDetails.setCheckedBinQtyAsString( lotDetails.getBinQtyAsString() );
                            }
                            
                            //int lotSize = 4000;

                            //int noofWafers = DataEntryDAO.getNoOfWafersPerLot(NewProductDAO.getForwardOrBackwardProcessstepId( dbTranasaction, Integer.parseInt(lotDetails.getProcessStepId()), 0, LOCATION_TYPE_FAB ));
                             //--START--
                            // TO UPDATE THE BIN QTY'S
                            sortBinlotDetails = new LotDetails();
                            sortBinlotDetails.setLotId( lotDetails.getLotId() );
                            sortBinlotDetails.setCheckedWaferIdsAsString( lotDetails.getCheckedWaferIdsAsString() );
                            sortBinlotDetails.setCheckedBinQtyAsString( lotDetails.getBinQtyAsString() );
                            sortBinlotDetails.setAssyReleased( lotDetails.isAssyReleased() );
                            waferInfoList.add( sortBinlotDetails );
                             //--END---


                            lotDetails.setShipDieQty( lotDetails.getDieQtyIn() );
                            lotDetails.setAssemblyLotNumber( lotDetails.getLotNumber() );

                            dbReceiveLotList.add( lotDetails );

                            /*if ( LOCATION_TYPE_ASSEMBLY.equalsIgnoreCase( lotDetails.getNextProcessType() ) *//*&& noofWafers > 0 *//* )
                            {
                                *//*int alphaBet;

                                String assemblyLotNo = DataEntryDAO.getLastGeneratedAssemblyLotNo( lotDetails.getLotNumber() );
                                assemblyLotNo = assemblyLotNo.substring( lotDetails.getLotNumber().length() );
                           
                                if ( assemblyLotNo != null && assemblyLotNo.length() == 1 )
                                {
                                    alphaBet = assemblyLotNo.charAt(0);
                                    alphaBet = alphaBet + 1;
                                    if ( (char)alphaBet == 'Z' )
                                    {
                                        alphaBet = '1';
                                    }
                                }
                                else
                                {
                                    alphaBet = 'A';
                                }

                                //int dieQtyIn  = Integer.parseInt( lotDetails.getDieQtyIn() );

                                //int lotNoSize   = dieQtyIn/lotSize;

                                int waferCount  = 0;
                                int quantity    = 0;

                                for( int id = 0 ; id < waferIDs.length; id++ )
                                {
                                    if ( waferIDs[id] != null && waferIDs[id] != ""  )
                                    {
                                        waferCount++;
                                        quantity  += Integer.parseInt( binQtys[id] );

                                        if ( waferCount == noofWafers || id == waferIDs.length )
                                        {
                                            waferCount = 0;

                                            newlotDetails = new LotDetails();

                                            //newlotDetails.setCheckedWaferIdsAsString( waferIDs[id] );
                                            newlotDetails.setPartNumber( lotDetails.getPartNumber());
                                            newlotDetails.setLotNumber( lotDetails.getLotNumber() );
                                            newlotDetails.setVendorName( lotDetails.getVendorName() );
                                            newlotDetails.setFabLotNumber(lotDetails.getFabLotNumber() );
                                            newlotDetails.setNextLocation(lotDetails.getNextLocation());
                                            newlotDetails.setLotId( lotDetails.getLotId() );
                                            newlotDetails.setNextProcessType( lotDetails.getNextProcessType() );
                                            newlotDetails.setAssemblyLotNumber( lotDetails.getLotNumber()+ (char)alphaBet );

                                            newlotDetails.setAssyLotSize( quantity );// FOR TEMPORARY
                                            newlotDetails.setShipDieQty( quantity+"");

                                            dbReceiveLotList.add( newlotDetails );
                                            //System.out.println("lotNumber = "+ lotDetails.getLotNumber()+ (char)alphaBet + "  QTY=" + secondlotSize );
                                             alphaBet++;
                                            quantity = 0;
                                        }
                                    }
                                }*//*
                                *//*for( int j=0; j < lotNoSize; j++ )
                                {
                                    newlotDetails = new LotDetails();

                                    //newlotDetails.setCheckedWaferIdsAsString( waferIDs[id] );
                                    newlotDetails.setPartNumber( lotDetails.getPartNumber());
                                    newlotDetails.setLotNumber( lotDetails.getLotNumber() );
                                    newlotDetails.setVendorName( lotDetails.getVendorName() );
                                    newlotDetails.setFabLotNumber(lotDetails.getFabLotNumber() );
                                    newlotDetails.setNextLocation(lotDetails.getNextLocation());
                                    newlotDetails.setLotId( lotDetails.getLotId() );
                                    newlotDetails.setNextProcessType( lotDetails.getNextProcessType() );
                                    newlotDetails.setAssemblyLotNumber( lotDetails.getLotNumber()+ (char)alphaBet );

                                    newlotDetails.setAssyLotSize( lotSize );// FOR TEMPORARY
                                    newlotDetails.setShipDieQty( lotSize+"");

                                    dbReceiveLotList.add( newlotDetails );
                                    //System.out.println("lotNumber = "+ lotDetails.getLotNumber()+ (char)alphaBet + "  QTY=" + secondlotSize );
                                     alphaBet++;
                                }
*//*
                                //For Remain Qty
                               *//* if ( dieQtyIn%lotSize != 0 )
                                {
                                    newlotDetails = new LotDetails();

                                    //newlotDetails.setCheckedWaferIdsAsString( waferIDs[id] );
                                    newlotDetails.setPartNumber( lotDetails.getPartNumber());
                                    newlotDetails.setLotNumber( lotDetails.getLotNumber() );
                                    newlotDetails.setVendorName( lotDetails.getVendorName() );
                                    newlotDetails.setFabLotNumber(lotDetails.getFabLotNumber() );
                                    newlotDetails.setAssyLotSize( lotSize );// FOR TEMPORARY
                                    newlotDetails.setNextLocation(lotDetails.getNextLocation());
                                    newlotDetails.setLotId( lotDetails.getLotId() );
                                    newlotDetails.setNextProcessType( lotDetails.getNextProcessType() );
                                    newlotDetails.setAssemblyLotNumber( lotDetails.getLotNumber() + (char)alphaBet );

                                    newlotDetails.setShipDieQty( (dieQtyIn%lotSize)+"");

                                    dbReceiveLotList.add( newlotDetails );
                                    //System.out.println(" REMAIN QTY lotNumber = "+ lotDetails.getLotNumber()+ (char)alphaBet + "  QTY=" + Integer.parseInt( binQtys[id] )%lotSize );
                                }*//*
                                *//*for( int id = 0 ; id < waferIDs.length; id++ )
                                {
                                    if ( waferIDs[id] != null && waferIDs[id] != ""  )
                                    {
                                        int noOflotsBySize   = Integer.parseInt( binQtys[id] )/lotSize;

                                        for( int j=0; j < noOflotsBySize; j++ )
                                        {
                                            newlotDetails = new LotDetails();

                                            newlotDetails.setCheckedWaferIdsAsString( waferIDs[id] );
                                            newlotDetails.setPartNumber( lotDetails.getPartNumber());
                                            newlotDetails.setLotNumber( lotDetails.getLotNumber() );
                                            newlotDetails.setVendorName( lotDetails.getVendorName() );
                                            newlotDetails.setFabLotNumber(lotDetails.getFabLotNumber() );
                                            newlotDetails.setNextLocation(lotDetails.getNextLocation());
                                            newlotDetails.setLotId( lotDetails.getLotId() );
                                            newlotDetails.setProcessType( lotDetails.getProcessType() );
                                            newlotDetails.setAssemblyLotNumber( lotDetails.getLotNumber()+ (char)alphaBet );
                                            newlotDetails.setAssyLotSize( lotSize );// FOR TEMPORARY
                                            newlotDetails.setShipDieQty( lotSize+"");

                                            dbReceiveLotList.add( newlotDetails );
                                            //System.out.println("lotNumber = "+ lotDetails.getLotNumber()+ (char)alphaBet + "  QTY=" + secondlotSize );
                                             alphaBet++;
                                        }

                                        if ( Integer.parseInt( binQtys[id] )%lotSize != 0 )
                                        {
                                             newlotDetails = new LotDetails();

                                             newlotDetails.setCheckedWaferIdsAsString( waferIDs[id] );
                                             newlotDetails.setPartNumber( lotDetails.getPartNumber());
                                             newlotDetails.setLotNumber( lotDetails.getLotNumber() );
                                             newlotDetails.setVendorName( lotDetails.getVendorName() );
                                             newlotDetails.setFabLotNumber(lotDetails.getFabLotNumber() );

                                             newlotDetails.setAssyLotSize( lotSize );// FOR TEMPORARY
                                             newlotDetails.setNextLocation(lotDetails.getNextLocation());
                                             newlotDetails.setLotId( lotDetails.getLotId() );
                                             newlotDetails.setProcessType( lotDetails.getProcessType() );
                                             newlotDetails.setAssemblyLotNumber( lotDetails.getLotNumber() + (char)alphaBet );

                                              newlotDetails.setShipDieQty( (Integer.parseInt( binQtys[id] )%lotSize)+"");

                                              dbReceiveLotList.add( newlotDetails );
                                             //System.out.println(" REMAIN QTY lotNumber = "+ lotDetails.getLotNumber()+ (char)alphaBet + "  QTY=" + Integer.parseInt( binQtys[id] )%lotSize );
                                        }
                                     }
                                     alphaBet++;
                                }*//*
                           }
                           else
                           {
                                lotDetails.setShipDieQty( lotDetails.getDieQtyIn() );
                                lotDetails.setAssemblyLotNumber( lotDetails.getLotNumber() );

                                dbReceiveLotList.add( lotDetails );
                           }*/
                        }
                    }
                }
                dieBankTransitForm.setWaferInfoList(  waferInfoList );
                dieBankTransitForm.setConfirmWipLotsList( dbReceiveLotList );
                saveToken( request );
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        else if ( action.equalsIgnoreCase("confirm") )
        {
            actionForword = "success";
            try
            {
                if ( isTokenValid( request ) )
                {
                    DataEntryDAO.saveDieBankTransitInfo( dbTranasaction, dieBankTransitForm.getConfirmWipLotsList(), user.getUserName() );

                    if ( dieBankTransitForm.getWaferInfoList() != null && dieBankTransitForm.getWaferInfoList().size() > 0 )
                    {
                        DataEntryDAO.updateDieBankTransitBinInfo( dieBankTransitForm.getWaferInfoList() );
                    }
                    resetToken( request );
                    info.put("Transit Lots info saved Successlly", null);
                }
                else
                {
                    errors.put("Invalid Request" , null );
                }

            }
            catch(Exception e)
            {
               e.printStackTrace();
               errors.put("Unable to save the Transit lots to Diebank" , null );
            }

            dieBankTransitForm.setProcessStepId(0);
            dieBankTransitForm.setLocationId(0);
            dieBankTransitForm.setLotId(0);
            dieBankTransitForm.setWipLotsList( null );
            dieBankTransitForm.setAssyRelease( true );
            
            if ( user.getVendorId() > 0 ) // for VENDOR INTERFACE
            {
                if (dieBankTransitForm.getLocationId() == 0 )
                {
                    vendorList = VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_DIE_BANK, user.getVendorId() );
                    if ( vendorList != null && vendorList.size() > 0 )
                    {
                        dieBankTransitForm.setLocationId( Integer.parseInt ( ( (LabelValueBean)vendorList.get(0) ).getValue() ) );
                    }
                    else
                    {
                        dieBankTransitForm.setLocationId( -1 );
                    }
                }
            }
            request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
            request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_DIE_BANK, user.getVendorId() ) );
            request.setAttribute("lotsList", DataEntryDAO.loadAllDieBankWipLots( 0, dieBankTransitForm.getLocationId(), 0, dieBankTransitForm.isAssyRelease()  ) );
        }

        return (mapping.findForward ( actionForword ) );
    }
}
